import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/store/user'

// 路由组件懒加载
const Login = () => import('@/views/Login.vue')
const Register = () => import('@/views/Register.vue')
const Layout = () => import('@/views/Layout.vue')
const Dashboard = () => import('@/views/Dashboard.vue')
const Profile = () => import('@/views/Profile.vue')
const HealthRecord = () => import('@/views/Health.vue')
const DietRecord = () => import('@/views/Diet.vue')
const ExerciseRecord = () => import('@/views/Exercise.vue')

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { requiresAuth: false }
  },
  {
    path: '/register',
    name: 'Register',
    component: Register,
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    meta: { requiresAuth: true },
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: Dashboard,
        meta: { title: '健康概览', icon: 'House' }
      },
      {
        path: 'profile',
        name: 'Profile',
        component: Profile,
    
      },
      {
        path: 'health',
        name: 'HealthRecord',
        component: HealthRecord,
        meta: { title: '智能规划', icon: 'Document' }
      },
      {
        path: 'diet',
        name: 'DietRecord',
        component: DietRecord,
        meta: { title: '饮食记录', icon: 'Food' }
      },
      {
        path: 'exercise',
        name: 'ExerciseRecord',
        component: ExerciseRecord,
        meta: { title: '运动记录', icon: 'Trophy' }
      },
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - 护康AI贴心助手` : '护康AI贴心助手'
  
  // 检查是否需要登录
  const requiresAuth = to.meta.requiresAuth !== false // 默认需要登录
  const isLoggedIn = userStore.isLoggedIn
  
  // 如果需要登录但用户未登录
  if (requiresAuth && !isLoggedIn) {
    // 避免从登录页重定向到登录页
    if (to.path !== '/login') {
      next('/login')
    } else {
      next()
    }
  } 
  // 如果已登录且访问的是登录或注册页
  else if (isLoggedIn && (to.path === '/login' || to.path === '/register')) {
    next('/dashboard')
  } 
  // 其他情况正常导航
  else {
    next()
  }
})

export default router